<?php
class InfoApp extends CommonApp {

	/**
	 * 首页
	 */
	public function indexAct(){
		$table = (My::arr2var($_REQUEST,'table')) ? My::arr2var($_REQUEST,'table') : 'homeuser';
		$search = array();
		$search['where'] = "1 ";
		if(My::arr2var($_REQUEST,'table') == 'tutor'){
			$table = 'homeuser';
			$search['where'] .= "AND complete_tutor=2 ";
		}
		if(!My::is_table($table))
			$this->ajaxReturn(404,'表名分类有误!');
		$type = My::arr2var($_REQUEST,'type');
		if($type === '0' || $type === '1')
			$search['where'] .= "AND type={$type} ";
		if(My::arr2var($_GET,'publish')==='0'){
			$search['where'] .= "AND publish=0 ";
		}elseif(My::arr2var($_GET,'publish')==1){
			$search['where'] .= "AND publish=1 ";
		}
		//搜索id
		if(My::is_id(My::arr2var($_GET,'id'))){
			$id = $_GET['id'];
			$search['where'] .= "AND `id`='{$id}' ";
		}
		//搜索姓名
		if(My::arr2var($_GET,'username')!=''){
			$username = $_GET['username'];
			$search['where'] .= "AND `username` like '%{$username}%' ";
		}
		$college = '';
		if(My::user('role_id')!=1){
			switch (My::user('userid')) {
				case '5':
					$college = '344';
					break;
				case '6':
					$college = '345';
					break;
				case '7':
					$college = '346';
					break;
				case '8':
					$college = '347';
					break;
				case '9':
					$college = '348';
					break;
				case '10':
					$college = '349';
					break;
				case '11':
					$college = '350';
					break;
				case '12':
					$college = '351';
					break;	
				case '13':
					$college = '352';
					break;	
				case '14':
					$college = '354';
					break;	
				case '15':
					$college = '355';
					break;	
				case '16':
					$college = '357';
					break;	
				case '17':
					$college = '353';
					break;	
				default:
					# code...
					break;
			}
		}elseif(My::arr2var($_GET,'college')!='')
			$college = $_GET['college'];
		//搜索学院
		if($college)
			$search['where'] .= "AND `college_id` like '%{$college}%' ";
		if(isset($_GET['order'])){
			$order = $_GET['order'];
			//排序字段为指派，正向排序为：当前用户最前，关闭最后，然后按照id正序排列
			$search['order'] = ($order=='assign') ? "`assign`={$userid} DESC, `assign`=0 ASC,`assign` DESC,`id` DESC" : $search['order'] = "`{$order}` DESC";
			//设置的字段排序与当前cookie排序一样的时候反向排序
			if(isset($_COOKIE['order']) && $search['order']==$_COOKIE['order']){
				//排序字段为指派，反向排序为：关闭最前，当前用户最后，然后按照id反序排列
				$search['order'] = ($order=='assign') ? "`assign`=0 DESC, `assign`={$userid} ASC,`assign` ASC,`editdate` DESC" : "`{$order}` ASC";
			}
			//字段排序存储cookie值一年
			setcookie('order', $search['order'], time()+31536000,'/');
			$this->ajaxReturn(200,'排序成功!');
		} else $search['order'] = isset($_COOKIE['order']) ? $_COOKIE['order'] : '`id` DESC';
		if(isset($_COOKIE['order']))
			$this->assign('order',$_COOKIE['order']);
		$search['page'] = My::arr2var($_REQUEST,'page').(isset($_SESSION['pagesize'])?$_SESSION['pagesize']:'');//用于参与缓存标识
		$search['pagesize'] = isset($_COOKIE['pagesize']) ? $_COOKIE['pagesize'] : '';
		$result = array();
		if(empty($result)){
			//page
			$count = DB($table)->where($search['where'])->count();
			$result['page'] = My::page($count,array('pagesize'=>$search['pagesize']));//分页
			//result
			$result['data'] = DB($table)->where($search['where'])->order($search['order'])->limit($result['page']['limits'])->select();//列表
			//college
			$result['college'] = M('admin.category')->item2submenu('college',array('level'=>'1'));//学院
			if(is_array($result['data']))
				foreach($result['data'] as &$value){
					unset($value['password']);
					$value['params'] = My::decodeJson($value['params']);
					if(isset($value['userid']))
						$value['user'] = DB('homeuser')->where("id={$value['userid']}")->field('username,mobile')->find();
					if(isset($value['teacher_id']))
						$value['teacher_name'] = DB('homeuser')->where("id={$value['teacher_id']}")->getField('username');
					if(isset($value['params_tutor']))
						$value['params_tutor'] = My::decodeJson($value['params_tutor']);

				}
			My::setCache($search,$result,array('pre'=>$table));
		}
		$table = (My::arr2var($_REQUEST,'table')) ? My::arr2var($_REQUEST,'table') : 'homeuser';
		$this->assign('result',$result);
		$this->display("Info/{$table}/index");
	}
	
	/**
	 * 查看
	 */
	public function modifyAct(){
		$table = (My::arr2var($_REQUEST,'table')) ? My::arr2var($_REQUEST,'table') : 'homeuser';
		if(My::arr2var($_REQUEST,'table') == 'tutor')
			$table = 'homeuser';
		if(!My::is_table($table))
			$this->ajaxReturn(404,'表名分类有误!');
		$type = My::arr2var($_REQUEST,'type');
		$id = I('get.id');
		$data = '';
		if(My::is_id($id)){
			$result = DB($table)->where("id={$id}")->find();
			$result['params'] = My::decodeJson($result['params']);
			if(isset($result['params']['indentify']))
				$result['params']['indentify'] = substr_replace($result['params']['indentify'],'***********','4','10');
			$result['log'] = My::decodeJson($result['log']);
			if(isset($result['userid']))
				$data = DB('homeuser')->where("id={$result['userid']}")->field('username,sex,email,mobile')->find();
			if($data){
				$result['username'] = $data['username'];
				$result['sex'] = $data['sex'];
				$result['email'] = $data['email'];
				$result['mobile'] = $data['mobile'];
			}
			$result['college_name'] = My::id2field('category',$result['college_id'],'title');
			if(isset($result['params_tutor']))
				$result['params_tutor'] = My::decodeJson($result['params_tutor']);
			unset($result['password']);
		}
		$table = (My::arr2var($_REQUEST,'table')) ? My::arr2var($_REQUEST,'table') : 'homeuser';
		$this->assign('result',$result);
		$this->display("Info/{$table}/modify");
	}

	/**
	 * 审核
	 */
	public function passAct(){
		//1为最高权限,
	 	if(My::user('role_id')!='1') $power = I('post.power_1');
	 	else $power = I('post.power_2');
	 	if(My::is_id($power) && $power == '2')
			$this->ajaxReturn(301,'审核已通过，请勿重新操作！');
	 	if(My::is_id($_POST['id'])){
	 		$date = date('Y-m-d H:i:s');
	 		$result = DB('homeuser')->clear()->where("id={$_POST['id']}")->field('id,username,email,log,power_1,power_2')->find();
	 		$result['log'] = My::decodeJson($result['log']);
	 		$log = array('date'=>'['.$date.']，'.'由“'.My::user('username').'”修改教师审核结果，旧值为“审核不通过”，新值为“审核通过”。');//对应数据表进行存储
	 		$result['log']['tutor'] = self::log2length($result['log']['tutor'],$log);
	 		$result['log']['tutor'][] = $log;
	 		if(My::user('role_id')!='1') $result['power_1'] = '2';
	 		else $result['power_2'] = '2';
	 		if($result['power_2'] == '2' && $result['power_1'] == '2'){
	 			$notice = array('date'=>$date,'detail'=>"您的导师申请结果为通过，详细情况已通过邮件发送！");
	 			$result['log']['notice'] = self::log2length($result['log']['notice'],$notice);
	 			$result['log']['notice'][] = $notice;
	 		}
			$emailParam['receiver'] = array($result['email']);
			$emailParam['title'] = '审核结果回复';
			$content = '恭喜您，'.$result['username'].'，成为了创新创业学院指导老师';
			$emailParam['content'] = "<br>------------------ 原始留言 ------------------<br><div style='font-size: 12px; background: #efefef; padding: 8px;'>{$content}</div>";
			$emailParam['host'] = C('email_host');
        	$ok_n = DB('homeuser')->clear()->clear()->save($result);//老师通知公告进行编辑
            if($ok_n){
            	$sendok = My::sendMail($emailParam);
            	if($sendok == true) $this->ajaxReturn(200,'已修改审核结果！');
            	else $this->ajaxReturn(300,'邮件发送失败！');
			}else $this->ajaxReturn(300,'审核错误，请重新操作！');
	 	}else
	 		$this->ajaxReturn(300,'id参数有误，请重新操作！');
	}

	/**
	 * 审核不通过
	 */
	 public function failedAct(){
	 	//1为最高权限,
	 	if(My::user('role_id')!='1') $power = I('post.power_1');
	 	else $power = I('post.power_2');
	 	if(My::is_id($power) && $power == '1')
			$this->ajaxReturn(301,'审核已不通过，请勿重新操作！');
	 	if(My::is_id($_POST['id'])){
	 		$date = date('Y-m-d H:i:s');
	 		$result = DB('homeuser')->clear()->where("id={$_POST['id']}")->field('id,username,email,notice,log,power_1,power_2')->find();

	 		$result['log'] = My::decodeJson($result['log']);
	 		$log = array('date'=>'['.$date.']，'.'由“'.My::user('username').'”修改教师审核结果，旧值为“审核通过”，新值为“审核不通过”。','detail'=>$_POST['content']);//对应数据表进行存储
	 		$notice = array('date'=>$date,'detail'=>"您的导师申请结果为不通过，详细情况已通过邮件发送！");
	 		$result['log']['notice'] = self::log2length($result['log']['notice'],$notice);
	 		$result['log']['tutor'] = self::log2length($result['log']['tutor'],$log,'1000');
	 		$result['log']['tutor'][] = $log;
	 		$result['log']['notice'][] = $notice;
			$emailParam['receiver'] = array($result['email']);
			$emailParam['title'] = '审核结果回复';
			if(!My::is_string($_POST['content']))
				$this->ajaxReturn(300,'请填写审核不通过的原因！');
			$emailParam['content'] = "<br>------------------ 原始留言 ------------------<br><div style='font-size: 12px; background: #efefef; padding: 8px;'>{$_POST['content']}</div>";
        	$emailParam['host'] = C('email_host');
        	if(My::user('role_id')!='1') $result['power_1'] = '1';
	 		else $result['power_2'] = '1';
        	$ok_n = DB('homeuser')->clear()->clear()->save($result);//老师通知公告进行编辑
            if($ok_n){	
            	$sendok = My::sendMail($emailParam);
            	if($sendok == true) $this->ajaxReturn(200,'已修改审核结果！');
            	else $this->ajaxReturn(300,'邮件发送失败！');
            }else $this->ajaxReturn(300,'审核错误，请重新操作！');
	 	}else
	 		$this->ajaxReturn(300,'id参数有误，请重新操作！');
	 }	

	/**
	 * 导出excel
	 */
	function excelAct(){
		$check_id = explode(",",$_GET['check_id']);
		foreach($check_id as $value)
			if(!My::is_id($value))
				$this->ajaxReturn(300,'ID有误!');;
		$where = " `id` IN (".$_GET['check_id'].")";
		if(DB($_GET['table'])->where($where)->count()==0)
			$this->ajaxReturn(300,'数据不存在!');
		$result = DB($_GET['table'])->where($where)->select();
		if(!$result OR !is_array($result))
			$this->ajaxReturn(300,'没有可导出的数据!');
		set_time_limit(0);
		$sex = C('sex');
		if($_GET['table'] != 'homeuser')
			foreach($result as &$value){
				$value['username'] = My::id2field('homeuser',$value['userid'],'username');
				$value['college'] = My::id2field('category',$value['college_id'],'title');
				$value['email'] = My::id2field('homeuser',$value['userid'],'email');
				$value['sex'] = $sex[My::id2field('homeuser',$value['userid'],'sex')];
				$value['mobile'] =  My::id2field('homeuser',$value['userid'],'mobile');
			}
		else
			foreach($result as &$value){
				$value['college'] = My::id2field('category',$value['college_id'],'title');
				$value['sex'] = $sex[$value['sex']];
			}
		$data[0] = array(
			'id' => 'ID',
			'username' => '姓名',
			'college' => '所属学院',
			'email' => '邮箱',
			'sex' => '性别',
			'mobile' => '联系方式',
		);
		foreach($result as &$value){
			$value['params'] = My::decodeJson($value['params']);
			$value = My::customSort($value,array_flip($data[0]),true);
		}
		$data = array_merge($data, $result);
		$filename = 'cxcyxy_'.date('YmdHis');
		$filename = iconv('UTF-8','GBK',$filename);//转GBK编码，当$filename是中文的时候需要这行，不然会乱码
		$savepath = DATA_DIR.'/Cache/';
		$xls = new Excel('UTF-8', false, 'VOLUNTEER');
		$xls->addArray($data);
		$xls->saveXLS($filename, $savepath);
		$xls->downloadXLS($savepath.$filename, $filename);
		die;
	}

	/**
	 * 审核日志
	 */
	public function log2length($array,$log,$length = '1500'){
		$array2 = $array;
		if(strlen(My::encodeJson($array2)) + strlen(My::encodeJson($log)) >= $length){
            array_shift($array2);
            $result =  self::log2length($array2,$length);
            return $result;
        }
        return $array2;
	}
}